package uit.edu.vn.Activity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import uit.edu.vn.Model.FileObject;
import uit.edu.vn.Model.myFile;
import uit.edu.vn.Utility.AESControl;
import uit.edu.vn.Utility.CheckInternet;
import uit.edu.vn.Utility.MyActivity;
import uit.edu.vn.Utility.WebService;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnClickListener;
import android.content.res.Resources;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class FileRestoreActivity extends MyActivity {
	
	private ListView listview;
	private Context context;
	private Resources res;
	private String path=Environment.getExternalStorageDirectory()+"/BackupManager/File";
	private ArrayList<myFile> listFiles = new ArrayList<myFile>();
	private int numberOfItemSelected = 0;	
	private ArrayAdapter<myFile> arrayAdapter;
	private ArrayList<FileObject> flist = new ArrayList<FileObject>();
	private int type = 3;
	private TextView titleHeader;
	public int totalSize;
	public int len =0;
	public InputStream in;
	public File output;
    private String userid = "";
    private String username = "";
    private String password = "";
    private static final String STRING_NAME_USERSETTING = "USER REFERENCES";
    private SharedPreferences ShareRef = null;
    private AESControl aes;
	private ProgressDialog loadingFileDialog;
	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		
        username = getSetting("username");
        password = getSetting("password");
        userid   = getSetting("userid");		
		
		setContentView(R.layout.backup_file);
	      //kiem tra neu username va password rong thi ket thuc activity hien tai va goi activity login
	    if(username.equals("") && password.equals("")){
	    	Intent intent = new Intent(FileRestoreActivity.this, LoginActivity.class);
	    	startActivity(intent);
	    	this.finish();            	
	    }
	    System.out.println("FileRestoreActivity");
	    System.out.println("username: "+ username);
	    System.out.println("password: "+ password);
	    System.out.println("userid:   "+ userid);	  
	    System.out.println("MainActivity.address.toString() : " + MainActivity.address.toString());
	      
		File dir = new File(path);
		dir.mkdirs();
		listview =(ListView) findViewById(R.id.listFileBackup);
        res=getResources();	
        context=getBaseContext();	
        titleHeader=(TextView)findViewById(R.id.txt_titleFile);
  		titleHeader.setText(R.string.title_RestoreHeaderFile);
		
        loadingFileDialog= new ProgressDialog(this);
        loadingFileDialog.setMessage(getResources().getString(R.string.dialog_message_progress_server));
        loadingFileDialog.setCancelable(false);
        loadingFileDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
    	CheckInternet chkI= new CheckInternet(context);
        if(chkI.checkStatus().equals(true))
		{

        	new BackgroundTask().execute();		
        	
		}
        else
        {
        	Log.d("ketnoi", "ko co ket noi internet");
        	showToast("Khong co ket noi internet");
        
        }
        listview.setOnItemClickListener(new OnItemClickListener() 
        {
     	   @Override
     	   public void onItemClick(AdapterView<?> arg0, View arg1, final int position,
 			long arg3) {
     		   
     		   	try {
     		   		
							// TODO Auto-generated method stub

							myFile entry = listFiles.get(position);
							File temp = new File(entry.getPath());
							String day=flist.get(position).dayBackupFile;
							System.out.println(flist.get(position).getFileName());
							System.out.println(day);
							final Dialog dialog=new Dialog(FileRestoreActivity.this);
			 	    		dialog.setContentView(uit.edu.vn.Activity.R.layout.file_dialog_server);
			 	    		dialog.setTitle("Thông tin tập tin ");
			 	    		TextView txt_filename= (TextView)dialog.findViewById(R.id.txt_filenameDialog);
			 	    		TextView txt_filesize= (TextView)dialog.findViewById(R.id.txt_filesizeDialog);
			 	    		TextView txt_fileday=(TextView)dialog.findViewById(R.id.txt_filedayDialog);
			 	    		txt_fileday.setText(day);
			 	    		txt_filename.setText(entry.getName().toString());
			 	    		int size_temp=Integer.parseInt(entry.getSize());
			 	    		System.out.println(size_temp);
		                	if(size_temp<1024)
		                	{
		                		txt_filesize.setText(entry.getSize()+" Byte");   
		                	}
		                	else if(size_temp<1048576)
		                	{
		                		System.out.println(size_temp);
		                		size_temp=size_temp/1024;
		                		System.out.println(size_temp);
		                		txt_filesize.setText(size_temp+" KB"); 
		                	}
		                	else
		                	{
		                		size_temp=size_temp/1048576;
		                		txt_filesize.setText(size_temp+" MB"); 
		                	}
//			 	    		txt_filesize.setText(entry.getSize()+"byte");
			 	    		
			 	    		Button btn_ok = (Button)dialog.findViewById(R.id.btn_okDialog);
			 	    		btn_ok.setOnClickListener(new View.OnClickListener() {
								
								@Override
								public void onClick(View v) {
									// TODO Auto-generated method stub
									dialog.dismiss();
								}
							});
			 	    		dialog.show();
						}
				
     		   	 catch (Exception e) {
					// TODO: handle exception
					  e.printStackTrace();
				}
     		   	
		
     	   }
        });
					
	}
	
	public String getSetting(String key) {
        ShareRef = getSharedPreferences(STRING_NAME_USERSETTING, Context.MODE_WORLD_WRITEABLE);
        return ShareRef.getString(key, "");
	}     
	
    private class BackgroundTask extends AsyncTask<Void, Void, Void>
    {
    	@Override
    	protected void onPreExecute() {
    		// TODO Auto-generated method stub
    		super.onPreExecute();
    		loadingFileDialog.show();
    	}
    	@Override
    	protected Void doInBackground(Void... params) {
    		// TODO Auto-generated method stub
    		try {
    			flist = WebService.getAllList(Integer.parseInt(userid), type);
    			for(int i = 0;i<flist.size(); i++){
    				System.out.println("file name is: "+flist.get(i).getFileName());
    			}
    			convert(flist);//convert tu fileObject sang myFile
    			
    		} catch (Exception e) {
    			// TODO: handle exception
    			e.printStackTrace();
    		}
    		return null;
    	}
    	@Override
    	protected void onPostExecute(Void result) {
    		// TODO Auto-generated method stub
    		loadingFileDialog.dismiss();
    		for(int j=0;j<listFiles.size();j++){
    			String temp = listFiles.get(j).getName().toString().trim();
    			temp = temp.replaceAll("@", " ");
    			listFiles.get(j).setName(temp);
    		}
    		arrayAdapter = new ArrayAdapter<myFile>(context, R.layout.row_file, listFiles) {
	            @Override
	            public View getView(int position, View v, ViewGroup parent) {
	                if (v == null) {
	                    LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	                    v = vi.inflate(R.layout.row_file, null);
	                }
	                myFile ffile = listFiles.get(position);                
	                if(ffile!=null){
	                    TextView tx_fileName = (TextView)v.findViewById(R.id.txt_fileName);
	                    TextView tx_size = (TextView)v.findViewById(R.id.txt_filePath);
	                    ImageView iv = (ImageView) v.findViewById(R.id.img_fileIcon);
	                 //   iv.setImageDrawable(res.getDrawable(R.drawable.ic_text));
	                    iv.setImageDrawable(ffile.getIcon());
	                    CheckBox chkSelect = (CheckBox) v.findViewById(R.id.chkSelectFile);
	                    chkSelect.setChecked(false);

	                	tx_fileName.setText(ffile.getName());
	                	int temp=Integer.parseInt(ffile.getSize());
	                	if(temp<1024)
	                	{
	                		tx_size.setText(ffile.getSize()+" Byte");   
	                	}
	                	else
	                	{
	                		temp=temp/1024;
	                		tx_size.setText(temp+" KB"); 
	                	}
	                	
	                	
	                  
	                }
	                return v;
	            }
			};

			countItemChecked();	 
			listview.setAdapter(arrayAdapter);

			super.onPostExecute(result);
    	}
    }
    //-----------------------------xu ly menu ------------------------------------------------
   
	public boolean onCreateOptionsMenu(Menu menu) 
	{
	    	// TODO Auto-generated method stub	    	
		new MenuInflater(getApplicationContext()).inflate(R.menu.restore_option_menu, menu);
		return super.onCreateOptionsMenu(menu);
	}
	
	public boolean onOptionsItemSelected(MenuItem item) 
	{
	    	// TODO Auto-generated method stub
	    switch(item.getItemId())
	    {
	    	case R.id.menu_restore_File:
	    		CheckInternet chkI= new CheckInternet(context);
    	        if(chkI.checkStatus().equals(false))
    			{
    				showAlertDialog(getResources().getString(R.string.dialog_thongbao), getResources().getString(R.string.dialog_message_ketnoi), new OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							dialog.cancel();
						
						}
					});
    			}
    	        else{
    	        	if(listFiles.isEmpty()){
    	        		showToast("Danh sách trống!");
    	        	} else if(numberOfItemSelected <= 0 ){
    	        		showToast("Vui lòng chọn tập tin cần sao lưu!");
    	        		}else if (numberOfItemSelected > 1 ){
    	    			showAlertDialog("Thông báo!", "Bạn chỉ phục hồi một tập tin ", new OnClickListener() {
							
							@Override
							public void onClick(DialogInterface dialog, int which) {
								// TODO Auto-generated method stub
								dialog.dismiss();
								
							}
						});
    	    			
    	    		}
    	    	else{
    	    		//xu ly phục hoi tập tin
    	    		showConfirmDialog(getResources().getString(R.string.dialog_thongbao),"Bạn muốn phục hồi tập tin này", new OnClickListener() 
    	    		{
					
    	    			@Override
    	    			public void onClick(DialogInterface dialog, int which) {
    	    				// TODO Auto-generated method stub
    	    				new AsyncTask<Void, Void, Void>()
    	    				{
							@Override
								protected void onPreExecute() {
								// TODO Auto-generated method stub
								super.onPreExecute();

						        loadingFileDialog.setMessage(getResources().getString(R.string.dialog_message_progress_server));
								loadingFileDialog.show();
							}	
								@Override
								protected Void doInBackground(Void... params) 
								{
									// TODO Auto-generated method stub
									try 
									{									
										Thread.sleep(1000);     
										//kiem tra file nao dc check 
										Log.d("listfile", String.valueOf(listFiles.size()));
										String urldownload = "http://"+getSetting("address")+"/ServerWeb/USERS/"+username+"/";
										for(int i=0;i<listFiles.size();i++)
										{
											FileObject entry=flist.get(i);
											if(listFiles.get(i).getChecked()==true)
											{
												Log.d("namefile", listFiles.get(i).getName());
												Log.d("urldownload: ", urldownload);
												
											
												String filename_temp=entry.getFileName().toString();
												System.out.println("file tam"+filename_temp);
												filename_temp=filename_temp.replaceAll(" ", "@");
														System.out.println("file tam"+filename_temp);
														urldownload = urldownload + 	filename_temp;
														Log.d("urldownload: ", urldownload);
//												restoreFromServer(entry.getPathFile(), entry.getFileName(), path);
											//	restoreFromServer(urldownload, listFiles.get(i).getName().toString(), path);
												restoreFromServer(urldownload, filename_temp, path);
												WebService.writeUserLog(entry.getFileID(), 2, "phuc hoi tap tin da sao luu tu may chu");
												String real_name=path+"/"+ listFiles.get(i).getName();
												System.out.println("ten that "+real_name);
												// xữ lý giãi mã 
												aes= new AESControl(username);
												Log.d("getpath",listFiles.get(i).getPath());
												Log.d("getName",filename_temp);
												//tao ra ten tam với khoảng trắng thay thế = @
												//String filename_temp=entry.getFileName().replaceAll("","@");
												String pathTemp=path+"/"+filename_temp;
												Log.d("pathtemp",pathTemp);
												String output = pathTemp.trim().replaceAll("@", " ");
												Log.d("out",output);
												aes.DecFile(pathTemp, output);
												File dec_file= new File(output);
												File temp = new File(pathTemp);
												temp.delete();
											//	dec_file.renameTo(new File(real_name));;																								
											}
										}
									}	 
									catch (Exception e)
									{
										// TODO Auto-generated catch block
										e.printStackTrace();
									}
								return null;
							}
							@Override
								protected void onPostExecute(Void result) 
							{
								// TODO Auto-generated method stub
								loadingFileDialog.dismiss();
								for(int j=0 ; j<listFiles.size() ; j++)
								{
									listFiles.get(j).setChecked(false);				
								}
								arrayAdapter.notifyDataSetChanged();
								numberOfItemSelected=0;
								showAlertDialog(getResources().getString(R.string.dialog_thongbao), getResources().getString(R.string.dialog_message_phuchoithanhcong), new OnClickListener() {
									
									@Override
									public void onClick(DialogInterface dialog, int which) {
										// TODO Auto-generated method stub
										dialog.dismiss();
									
									}
								});
								super.onPostExecute(result);
							}
						}.execute();
					}
    			
				});
    	    	}
    	        }
    	        return true;
	    	case R.id.menu_restore_Delete:
	    		if(listFiles.isEmpty())
	    		{
		    		showToast("Danh sách trống!");
		    	}
	    		else if(numberOfItemSelected <= 0 )
	    		{
		    		showToast("Vui lòng chọn tập tin cần xóa!!");
		    	}
	    		else if (numberOfItemSelected > 0 )
	    		{
					showConfirmDialog(getResources().getString(R.string.dialog_canhbao), getResources().getString(R.string.dialog_message_xoa), new OnClickListener() {
						public void onClick(DialogInterface dialog, int which) 
						{
							new AsyncTask<Void, Void, Void>()
							{
								@Override
								protected void onPreExecute() {
									// TODO Auto-generated method stub
									loadingFileDialog.setMessage("Đang xóa tập tin");
									loadingFileDialog.show();
									
									super.onPreExecute();
								}
								
								@Override
								protected Void doInBackground(Void... params) {
								// TODO Auto-generated method stub
									for(int i=0;i<listFiles.size(); i++){
										myFile mfile = listFiles.get(i);
										FileObject entry = flist.get(i);
										if(mfile.getChecked()){
											try {
												String msg = WebService.deleteFileById(entry.getFileID(), "xóa tập tin ");
												
												if(msg.equals("1")){
													listFiles.remove(mfile);
													flist.remove(entry);
													i--;
													numberOfItemSelected --;
												}
											} catch (Exception e) {
												// TODO Auto-generated catch block
												e.printStackTrace();
											}
										}
									}
								return null;
								}
								@Override
								protected void onPostExecute(Void result) {
									// TODO Auto-generated method stub
									super.onPostExecute(result);
									loadingFileDialog.dismiss();
									arrayAdapter.notifyDataSetChanged();
									showAlertDialog(getResources().getString(R.string.dialog_thongbao),getResources().getString(R.string.dialog_message_xoathanhcong), new OnClickListener() {
										
										@Override
										public void onClick(DialogInterface dialog, int which) {
											// TODO Auto-generated method stub
											arrayAdapter.notifyDataSetChanged();
											dialog.cancel();
										}
									});
								}
							}.execute();

						}
					});
		    	}
		    	return true;
	    	case R.id.menu_restore_Logout:	
	    		logOut();
	    		Intent intent = new Intent(FileRestoreActivity.this, LoginActivity.class);
	    		startActivity(intent);
	    		this.finish();
	    		return true;
	    	
	    }
	    return false;
	}
	//--------------------------------------các hàm xử lý khác------------------------------------
	 public void convert(ArrayList<FileObject> list){
	    	for(int i = 0;i<list.size(); i++)
	    	{
	    		String checkName;
	    		checkName=list.get(i).getFileName().toLowerCase();
	    		System.out.print(checkName);
	    		if(checkName.endsWith("mp3"))
	    		{
	    			listFiles.add(new myFile(list.get(i).getFileName(),list.get(i).getPathFile(),String.valueOf(list.get(i).getFileSize()), res.getDrawable(R.drawable.ic_music_selector)));
	    		}
	    		else if(checkName.endsWith("png")||checkName.endsWith("jpg")||checkName.endsWith("jpeg")||checkName.endsWith("jpg"))
	    		{
		    		listFiles.add(new myFile(list.get(i).getFileName(),list.get(i).getPathFile(),String.valueOf(list.get(i).getFileSize()), res.getDrawable(R.drawable.ic_image_selector)));
	    		}
	    		else
	    		{
		    		listFiles.add(new myFile(list.get(i).getFileName(),list.get(i).getPathFile(),String.valueOf(list.get(i).getFileSize()), res.getDrawable(R.drawable.ic_text)));
	    		}
	    	}	
	    }
	    private void countItemChecked() {
	        numberOfItemSelected = 0;
	        for (int i = 0; i < listFiles.size(); i++) {
	            if (listFiles.get(i).getChecked()) {
	                numberOfItemSelected++;
	            }
	        }
	    }
		
		
		public void CheckButtonOnClick(View v){
			CheckBox chk = (CheckBox) v;
			int pos = listview.getPositionForView(v);
			myFile file = arrayAdapter.getItem(pos);
			file.setChecked(chk.isChecked());
			numberOfItemSelected += chk.isChecked() ? 1 : -1;			
		}
		
		private static void restoreFromServer(String url, String fileName, String path){
			try{
				int lenght = 0;				
				File file = new File(path,fileName);	
				FileOutputStream fos = new FileOutputStream(file);
				System.out.println("url download file: "+url);
				System.out.println("path save file : "+path);
				//doi tuong urlconnection
		        URL u = new URL(url);
		        URLConnection urlconn = u.openConnection();
		        HttpURLConnection httpconn = (HttpURLConnection) urlconn;
		        httpconn.setRequestMethod("GET");
		        httpconn.setDoOutput(true);
		        httpconn.connect();
		        //lay ve doi tuong va dat trong inputStream
		        InputStream in = httpconn.getInputStream();
				lenght=httpconn.getContentLength();
									
				byte[] buffer = new byte[1024];
		        int len1 = 0;
		        long total = 0;

		        while ((len1 = in.read(buffer)) > 0) {
		            total += len1; 
		            fos.write(buffer, 0, len1);
		        }
		        fos.close();	  
		        System.out.println("length file : " + file.length());
			}catch (Exception e) {
				// TODO: handle exception
				Log.e("KQ1", e.toString());
			}
		}
	
	
}
